package com.baibei.ebec.user.address;

import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.View;
import android.widget.CheckBox;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.baibei.basic.IPresenter;
import com.baibei.ebec.user.R;
import com.baibei.ebec.user.R2;
import com.baibei.model.AddressInfo;
import com.baibei.module.AppRouter;
import com.baibei.module.BasicActivity;
import com.baibei.ui.AppUI;
import com.rae.widget.dialog.impl.ProvinceSelectionDialog;
import com.rae.widget.dialog.model.LocationProvinceInfoBean;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;


/**
 * 收货地址编辑
 * Created by ChenRui on 2016/8/13 0013.
 */
@Route(path = AppRouter.ROUTER_ADDRESS_EDIT)
public class AddressEditActivity extends BasicActivity
        implements AddressEditContract.View {

    /**
     * 更新操作
     */
    private static final int OPTION_UPDATE = 1;
    private static final int OPTION_ADD = 0;

    @BindView(R2.id.et_receiver_name)
    TextView mNameView;

    @BindView(R2.id.et_phone)
    TextView mPhoneView;

    @BindView(R2.id.et_address)
    TextView mAddressDetailView;
    @BindView(R2.id.et_zip_code)
    TextView mZipCodeView;


    @BindView(R2.id.et_city)
    TextView mAreaView; // 地区

    @BindView(R2.id.cb_address_info_default)
    CheckBox mCbDefaltSelect;


    private AddressInfo mAddressInfo;
    private int mOptionType;
    private AddressEditContract.Presenter mPresenter;
    private ProvinceSelectionDialog mProvinceSelectionDialog;
    private boolean mIsFirst;
    private boolean mIsDefault;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_address);

        mPresenter = inject(AddressEditContract.Presenter.class);

        mAddressInfo = getIntent().getParcelableExtra("data");
        mIsFirst = getIntent().getBooleanExtra("isFirst", false); // 是否为第一个地址
        if (mAddressInfo == null) {
            mAddressInfo = new AddressInfo();
            mOptionType = OPTION_ADD;
        } else {
            mOptionType = OPTION_UPDATE;
            mIsDefault = mAddressInfo.isDefault();
            setTitle("编辑地址");
        }

        // 初始化数据
        mNameView.setText(mAddressInfo.getReceiver());
        mPhoneView.setText(mAddressInfo.getMobile());
        mAreaView.setText(mAddressInfo.getRegion());
        mAddressDetailView.setText(mAddressInfo.getAddress());
        mZipCodeView.setText(mAddressInfo.getZipCode());
        mCbDefaltSelect.setChecked(mAddressInfo.isDefault());

        mPresenter.start();

    }

    @Override
    public IPresenter getBasicPresenter() {
        return mPresenter;
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        try {
            if (requestCode == 10086 && resultCode == RESULT_OK) {
                Uri contactData = data.getData();
                Cursor cursor = managedQuery(contactData, null, null, null,
                        null);
                cursor.moveToFirst();

                String userName = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));

                Cursor phoneCursor = managedQuery(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                        null,
                        ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + contactId,
                        null,
                        null);

                if (phoneCursor.moveToNext()) {
                    String phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                    phoneNumber = phoneNumber.replace(" ", "").replace("-", ""); // 去掉多于的符号
                    mPhoneView.setText(phoneNumber);
                    mNameView.setText(userName);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            AppUI.toast(getContext(), "获取联系人出错了，请手动输入。");
        }
    }

    // 地区联动选择
    @OnClick(R2.id.et_city)
    public void areaClick(View view) {
        if (mProvinceSelectionDialog != null) {
            String[] address = mAreaView.getText().toString().split(" ");

            String province = null;
            String city = null;
            String areas = null;

            for (int i = 0; i < address.length; i++) {
                String item = address[i];
                if (i == 0) {
                    province = item;
                } else if (i == 1) {
                    city = item;
                } else {
                    areas = item;
                }
            }

            mProvinceSelectionDialog.invalidate(province, city, areas);
            mProvinceSelectionDialog.show();
        } else {
            AppUI.toast(getContext(), "省市数据尚未准备好");
        }
    }

    @OnClick(R2.id.tv_save)
    public void saveClick(View view) {
        AppUI.loading(this, "正在保存地址");
        switch (mOptionType) {
            case OPTION_ADD:
                mPresenter.addAddress();
                break;
            case OPTION_UPDATE:
                mPresenter.updateAddress();
                break;
        }
    }

    @Override
    public AddressInfo getAddressInfo() {
        mAddressInfo.setReceiver(mNameView.getText().toString());
        mAddressInfo.setMobile(trim(mPhoneView.getText().toString()));
        mAddressInfo.setRegion(mAreaView.getText().toString());
        mAddressInfo.setAddress(mAddressDetailView.getText().toString());
        mAddressInfo.setDefault(mCbDefaltSelect.isChecked());
        mAddressInfo.setZipCode(mZipCodeView.getText().toString());
        return mAddressInfo;
    }

    @Override
    public void onAddAddressSuccess(AddressInfo data) {
        AppUI.dismiss();
        AppUI.toast(getContext(), "新增收货地址成功");
        Intent intent = new Intent();
        intent.putExtra("data", data);
        setResult(RESULT_OK, intent);
        finish();
    }

    @Override
    public void onUpdateAddressSuccess() {
        AppUI.dismiss();
        AppUI.toast(getContext(), "更新收货地址成功");

        Intent intent = new Intent();
        intent.putExtra("data", getAddressInfo());
        setResult(RESULT_OK, intent);
        finish();
    }

    @Override
    public void onAddAddressFailed(int i, String msg) {
        AppUI.dismiss();
        AppUI.toast(getContext(), msg);
    }


    @Override
    public void onUpdateAddressFailed(int i, String msg) {
        AppUI.dismiss();
        AppUI.toast(getContext(), msg);
    }

    @Override
    public void onLoadAreaDataFailed(String msg) {
        AppUI.dismiss();
        AppUI.toast(getContext(), msg);
    }

    @Override
    public void onLoadAreaDataSuccess(List<LocationProvinceInfoBean> data) {
        mProvinceSelectionDialog = new ProvinceSelectionDialog(getContext(), data);
        mProvinceSelectionDialog.setOnDismissListener(new ProvinceSelectionDialog.ProvinceSelectionDismissListener() {
            @Override
            public void onDismiss(String provinceName, String cityName, String areasName, String provinceId, String cityId, String areasId) {
                mAreaView.setText(String.format("%s %s %s", provinceName, cityName, areasName));
                mAddressInfo.setRegion(mAreaView.getText().toString());
            }
        });
    }

    /**
     * 字符串去空格
     *
     * @param str
     * @return
     */
    private String trim(String str) {
        return str.trim().replace(" ", "");
    }
}
